package programmierung.aufgabe3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import de.pdbm.ewn.Game;
import de.pdbm.ewn.Number;
import de.pdbm.ewn.RedOrBlue;

public class EWNIO {

	public void write(Game game, File file) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
		String[][] sField = game.getState();

		for (int i = 0; i < sField.length; i++) {
			for (int j = 0; j < sField[i].length; j++) {
				if (sField[i][j] != null) {
					bw.append(sField[i][j]);
					if (j < (sField[i].length - 1)) {
						bw.append(" ");
					}
					if (j == (sField[i].length - 1)) {
						bw.append(System.lineSeparator());
					}
				}
			}

		}

		bw.close();
	}

	public Game read(File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		EWN game = new EWN();
		String tempStr = br.readLine();
		String[] tempSplit;

		while (tempStr != null) {
			tempSplit = tempStr.split(" ");
			game.init(RedOrBlue.valueOf(tempSplit[0]),
					Number.valueOf(tempSplit[1]),
					Integer.parseInt(tempSplit[2]),
					Integer.parseInt(tempSplit[3]));
			tempStr = br.readLine();
		}
		return game;
	}
}
